package dao

import (
	"osiris/db"
	"osiris/logger"
	"osiris/model"

	peer "github.com/libp2p/go-libp2p/core/peer"
)

// GetFirstAddrByID  返回peers表中对应peerID的第一条数据
//
//	@param peerID
//	@return *model.PeerModel
//	@return error
func GetFirstAddrByID(peerID peer.ID) (model.AddrModel, error) {
	var addrModel model.AddrModel
	err := db.MySQL.Where("peerID = ?", peerID).First(&addrModel).Error
	return addrModel, err
}

// GetAddrsByID 返回peers表中对应peerID的所有数据
//
//	@param peerID
//	@return []model.PeerModel
//	@return error
func GetAddrsByID(peerID peer.ID) ([]model.AddrModel, error) {
	var addrModels []model.AddrModel
	err := db.MySQL.Where("peerID = ?", peerID).Find(&addrModels).Error
	return addrModels, err
}

// GetAllAddrs 返回peers表中所有数据
//
//	@return []model.PeerModel
//	@return error
func GetAllAddrs() ([]model.AddrModel, error) {
	var peerModels []model.AddrModel
	err := db.MySQL.Find(&peerModels).Error
	return peerModels, err
}

// AddAddrByModel 通过peerModel存储peer.ID-addr
//
//	@param model
//	@return error
func AddAddrByModel(model model.AddrModel) error {
	err := db.MySQL.Create(&model).Error
	if err != nil {
		logger.Error(map[string]interface{}{"[dao] [Add addr by model]": err})
		return err
	}

	logger.Info(map[string]interface{}{"[dao] [Add addr by model]": "success"})
	return nil
}

// AddPeerByDto 批量存储peer.ID-addrs
//
//	@param peerDto
//	@return error 只返回产生的第一个不为nil的错误
func AddAddrs(peerID peer.ID, addrStrs []string) error {
	if len(addrStrs) == 0 {
		return nil
	}

	peerIDStr := peerID.String()
	for _, addrStr := range addrStrs {
		err := AddAddrByModel(model.AddrModel{
			PeerIDStr:    peerIDStr,
			MultiaddrStr: addrStr,
		})
		if err != nil {
			return err
		}
	}

	return nil
}

// SaveAddr Save update value in database, if the value doesn't have primary key, will insert it
//
//	@param model model.AddrModel
//	@return error
func SaveAddr(model model.AddrModel) error {
	err := db.MySQL.Save(&model).Error
	return err
}

func DeleteAddr(peerIDstr string) error {
	err := db.MySQL.Delete(&model.AddrModel{}, "peerID = ?", peerIDstr).Error
	return err
}
